﻿using System.Xml;
using UnityEngine;

namespace UnityView.Xml
{
    public static class AttributeParser
    {
        public static bool HasKey(this XmlAttributeCollection attrs, string key)
        {
            return attrs[key] != null;
        }
    
        public static string TryGetString(this XmlAttributeCollection attrs, string key, string defaultValue = null)
        {
            var attr = attrs[key];
            if (attr == null) return defaultValue;
            return attr.Value;
        }
    
        public static int TryGetInt(this XmlAttributeCollection attrs, string key, int defaultValue = 0)
        {
            var attr = attrs[key];
            if (attr == null) return defaultValue;
            return int.Parse(attr.Value);
        }

        public static float TryGetFloat(this XmlAttributeCollection attrs, string key, float defaultValue = 0)
        {
            var attr = attrs[key];
            if (attr == null) return defaultValue;
            return float.Parse(attr.Value);
        }
        
        public static bool TryGetBool(this XmlAttributeCollection attrs, string key, bool defaultValue = false)
        {
            var attr = attrs[key];
            if (attr == null) return defaultValue;
            return "true" == attr.Value;
        }
        
        public static Vector2 TryGetVector2Int(this XmlAttributeCollection attrs, string key)
        {
            var attr = attrs[key];
            if (attr == null) return Vector2Int.zero;
            string[] s = attr.Value.Split(',');
            return new Vector2(int.Parse(s[0]), int.Parse(s[1]));
        }
    
        public static Frame TryGetFrame(this XmlAttributeCollection attrs, string key)
        {
            var attr = attrs[key];
            if (attr == null) return Frame.Zero;
            string[] s = attr.Value.Split(',');
            return new Frame(float.Parse(s[0]), float.Parse(s[1]), float.Parse(s[2]), float.Parse(s[3]));
        }
    }
}
